import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Buffer {
	static boolean isOrigBuffered;
	static boolean isTransBuffered;
	Document bufDoc;
	File bufFile;
	boolean fileIsNew;
	private String bufStr = "";
	private static final int THREE = 3, FOUR = 4, FIVE = 5, SIX = 6;
	public Buffer(String fnm){ //СОЗДАДИМ / ОБНОВИМ ФАЙЛ БУФЕРА
		bufFile=new File(fnm); //Возьмем файл с буфером
		try {
			BufferedReader br = new BufferedReader(new FileReader(bufFile));
			String nxLine = null;
			while (true){
				nxLine = br.readLine();
				if (nxLine == null) break;
				bufStr += nxLine;
			}
			FeedParserX bufD = new FeedParserX(bufStr);
			bufDoc = bufD.getDoc();
			br.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			bufDoc = createDoc();
			fileIsNew = true;
			toXml();
			//e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	String toStr () { return bufStr; }
	Document toDoc () { return bufDoc; }
	 void toXml () {
			try {
				Transformer xmlMaker = TransformerFactory.newInstance().newTransformer();
				try {
					xmlMaker.transform(new DOMSource(bufDoc), 
							new StreamResult(bufFile));
				} catch (TransformerException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (TransformerConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (TransformerFactoryConfigurationError e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
	Document createDoc() {
		try {
			DocumentBuilderFactory df = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = df.newDocumentBuilder();
			Document newDoc = db.newDocument();
			Element all = newDoc.createElement("all");
			newDoc.appendChild(all);
			return newDoc;
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
		
	}
	/** SIIN ME TEEME UUE PUHVRI XML-i (VAJADUSEL) 
	 * JA TAGASTAME LOETELU KUVAMISEKS
	 * */
	String [] mkArrayToOut ( Node nxPubDate, String lang) {
		String [] out = new String [SIX];
		NodeList bufDates = bufDoc.getElementsByTagName("date");
		Element curDate = null;
		isOrigBuffered = false;
		//kõigepealt saame teada, kas on see kuupaev puhverdatud 
		String dateInFeed = nxPubDate.getTextContent(); 
			// võtame iga kp feedist
		for (int j = 0; j < bufDates.getLength(); j++) { 
			String kpInBuf = bufDates.item(j).getAttributes().item(0).getTextContent();
			if (dateInFeed.equals(kpInBuf)){ // kui kuupäev on puhvris
				curDate = (Element) bufDates.item(j);
				out[3] = "b";
				isOrigBuffered = true;			// paneme triggerid
				break; // tsyklist valja
			} 
		}
		Node item = nxPubDate.getParentNode();
		Node kpv = ((Element) item).getElementsByTagName("pubDate").item(0);
		Node title = item.getChildNodes().item(0);
		Node sisu = item.getChildNodes().item(2);
		String kuupaev = kpv.getTextContent();
		if (!isOrigBuffered ){ // kui kuupaeva ei leitud siis paneme 
			out[3] = "nb";
			title = bufDoc.importNode(title, true); // paneme title puhvrisse
			sisu = bufDoc.importNode(sisu, true); 
			TransformHTML cleanSisu = new TransformHTML (sisu.getTextContent());
			sisu.setTextContent(cleanSisu.toStr());
			kpv = bufDoc.importNode(kpv, true); 
			Element link = bufDoc.createElement("link");
			link.setTextContent(cleanSisu.getLink()); // paneme sisu puhvrisse
							
			Element  language = bufDoc.createElement("lang"); // teeme uus solm
											
			language.setAttribute("value", "et");
			language.appendChild(title); 
			language.appendChild(kpv); 
			language.appendChild(sisu);
			language.appendChild(link);
			curDate = bufDoc.createElement("date"); // teeme uus kuupaeva solm
												
			curDate.setAttribute("value", kuupaev); // paneme value feedist.
			curDate.appendChild(language);
			bufDoc.getFirstChild().appendChild(curDate);
			//toXml( "test.xml"); //paneme puhvrisse
		}
		String link = curDate.getFirstChild().getChildNodes().item(3).getTextContent();
		sisu = curDate.getFirstChild().getChildNodes().item(2);
		out[5] =link;
		if (lang == "et") { //siis kuvame originaalkeeles
			out [0] = title.getTextContent();
			out [1] = kuupaev;
			out [2] = TransformHTML.format(sisu.getTextContent(), link);
			if (isOrigBuffered) out[4] = "b";
			else out [4] = "nb";
		} else { // siis kuvame tõlget
			NodeList langs = curDate.getChildNodes();
			Node each = null;
			for (int y = 0; y < langs.getLength(); y++) {
				each = langs.item(y);
				if (each.getAttributes().item(0).getTextContent().equals(lang)) {
					isTransBuffered = true;
					break;
				}
			}
			if (isTransBuffered){
				out [0] = each.getChildNodes().item(0).getTextContent();
				out [1] = kuupaev;
				out [2] = each.getChildNodes().item(2).getTextContent();
				out [4] = "b";
			}		else  {
				Translate curTr = new Translate(title.getTextContent(), lang);
				out [0] = curTr.toStr();
				Node titleTr  = bufDoc.createElement("title");
				titleTr.setTextContent(curTr.toStr());
				curTr = new Translate (kuupaev, lang);
				out [1] = curTr.toStr();
				Node kpTr  = bufDoc.createElement("pubDate");
				kpTr.setTextContent(curTr.toStr());
				curTr = new Translate (sisu.getTextContent(), lang);
				Node sisuTr  = bufDoc.createElement("description");
				sisuTr.setTextContent(curTr.toStr());
				out [2] = (new TransformHTML(sisuTr.getTextContent())).toStr();
				Node linkTr = bufDoc.createElement("link");
				linkTr.setTextContent(link);
				Element langTr = bufDoc.createElement ("lang");
				langTr.setAttribute("value", lang);
				langTr.appendChild(titleTr);
				langTr.appendChild(kpTr);
				langTr.appendChild(sisuTr);
				langTr.appendChild(linkTr);
				curDate.appendChild(langTr);
				out [4] = "nb";
			}
			isTransBuffered = false;
		}
	return out;
	}
}
